<?php

namespace app\index\service\wrappers;

use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\model\ConsultingReward;
use app\common\model\ConsultingServer;
use app\index\dao\ConsultingRewardDao;
use ShidianUtil\Utils\TimeUtil;

/**
 *
 * Class CommentMessageWrapper
 * @package app\consulting\service\wrappers
 */
class RewardMessageWrapper implements MessageWrapperInterface
{

    private ConsultingRewardDao $consultingRewardDao;

    public function __construct(ConsultingRewardDao $consultingRewardDao)
    {

        $this->consultingRewardDao = $consultingRewardDao;
    }

    /**
     * 包装动态消息
     * @param ConsultingMessage $message
     * @return void
     */
    public function wrapMessage(ConsultingMessage $message)
    {
        // 查询并获取 server 内容
        $content = [];
        $content['rewards'] = $this->consultingRewardDao->selectCardMessage();

        // 查询今天是否有剩余的免费咨询
        if ($this->hasFree($message->consultingId)) {
            $content['rewards']->push(new ConsultingReward([
                'name' => '免费咨询',
                'price' => 0.00,
            ]));
        }

        $message->set('content', $content);
    }

    /**
     * 批量包装动态消息
     * @param array $messages
     * @return void
     */
    public function wrapMessages(array $messages)
    {
        // 查询并获取 server 内容
        $content = [];
        $content['rewards'] = $this->consultingRewardDao->selectCardMessage();

        foreach ($messages as $message) {

            // 查询今天是否有剩余的免费咨询
            if ($this->hasFree($message['consultingId'])) {
                $new_content = $content;
                $new_content['rewards']->push(new ConsultingReward([
                    'name' => '免费咨询',
                    'price' => 0.00,
                ]));
                $message->set('content', $new_content);
            } else {

                $message->set('content', $content);
            }

        }
    }

    private function hasFree($consultingId)
    {

        $consulting = Consulting::where('id', $consultingId)->find();
        if ($consulting) {

            $server = ConsultingServer::where('id', $consulting->consultingServerId)
                ->where('serverType', ConsultingServer::FREE)
                ->find();

            if ($server && $server->maxTimes > 0) {

                $now = time();
                $count = Consulting::where('memberId', $consulting->memberId)
                    ->where('freeNum', '>', 0)
                    ->where('created', '>=', TimeUtil::stamp(TimeUtil::DAY, $now))
                    ->where('created', '<=', TimeUtil::stamp(TimeUtil::DAY, $now, false))
                    ->count();

                if ($count < $server->maxTimes) {
                    // 是免费咨询，且当天还有免费咨询次数

                    return true;
                }
            }
        }

        return false;
    }
}
